package com.example.demo.resource;

import com.example.demo.bean.Photo;
import com.example.demo.bean.PhotoTooLargeException;
import com.example.demo.service.PhotoService;
import com.example.demo.service.impl.PhotoServiceImpl;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.springframework.stereotype.Component;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Component
@Path("photos")
public class PhotoResource {

    private static PhotoService photoService = new PhotoServiceImpl();

    @POST
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces(MediaType.APPLICATION_JSON)
    public Map<String, Object> upload(@FormDataParam("file") File file, @FormDataParam("file")FormDataContentDisposition formDataContentDisposition){

        Photo photo = new Photo();

        Map<String, Object> map = new HashMap<>();

        try {
            photoService.upload(formDataContentDisposition.getFileName(), file);
            //删除缓存文件
            file.delete();
            //获取url
            String url = photoService.getUrl(photo.getPhotoName());
            photo.setPhotoName(formDataContentDisposition.getFileName());
            photo.setUrl(url);

            map.put("state", "ok");
            map.put("data", photo);
        } catch (PhotoTooLargeException e) {
            e.printStackTrace();
            map.put("state", "failed");
            map.put("msg", "photo is too large!");
        } catch (Exception e) {
            map.put("state", "failed");
            map.put("msg", e.getMessage());
        }
        return map;
    }

    @Path("hello")
    @GET
    public String hello(){
        return "123213";
    }

    @Path("{key}")
    @DELETE
    @Produces(MediaType.APPLICATION_JSON)
    public Map<String,Object> test(@PathParam("key") String key) {

        Map<String, Object> map = new LinkedHashMap<>();

        try {
            photoService.delete(key);
            map.put("state", "ok");
            map.put("msg", "删除成功");
        } catch (Exception e) {
            map.put("state","failed");
            map.put("msg", e.getMessage());
            e.printStackTrace();
        }
        return map;
    }


}
